<template>
  <a-layout class="layout">
    <a-layout-header class="layout_head">
      <div>
        <div @click="handleNewConnection">
          <img src="../assets/image/newConnect.svg" alt="#" style="height: 25px; width: 25px" />
          <div>新建连接</div>
        </div>
        <div @click="handleToQuery">
          <img src="../assets/image/query.svg" alt="#" style="height: 25px; width: 25px" />
          <div>新建查询</div>
        </div>
        <div>
          <img src="../assets/image/Table.svg" alt="#" style="height: 25px; width: 25px" />
          <div>超级表</div>
        </div>
        <div>
          <img src="../assets/image/Table.svg" alt="#" style="height: 25px; width: 25px" />
          <div>普通表</div>
        </div>
        <div>
          <a-button @click="handleQuery">查询</a-button>
        </div>
      </div>
    </a-layout-header>

    <a-layout-content>
      <ArcoSplit
        v-model:size="splitSize"
        :style="{
          height: '100%',
          width: '100%',
          minWidth: '500px',
          border: '1px solid var(--color-border)'
        }"
      >
        <template #first>
          <!--          <div style="height: 100%">左侧面板</div>-->
          <Sidebar ref="sidebarRef" />
        </template>
        <template #second>
          <div style="height: 100%">
            <router-view></router-view>
          </div>
        </template>
      </ArcoSplit>
    </a-layout-content>
  </a-layout>

  <!-- 新建连接 -->
  <a-modal
    v-model:open="newConnectionModal"
    title="新建连接"
    ok-text="确认"
    cancel-text="取消"
    @ok="handleSaveConn"
    @cancel="connectionOnFinish"
  >
    <a-form
      :model="connectionForm"
      name="newConn"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 16 }"
      autocomplete="off"
      @finish="connectionOnFinish"
    >
      <a-form-item
        label="连接名称"
        name="connectionName"
        :rules="[{ required: true, message: '请输入连接名称!' }]"
      >
        <a-input v-model:value="connectionForm.connectionName" />
      </a-form-item>

      <a-form-item label="IP地址" name="ip" :rules="[{ required: true, message: '请输入IP地址!' }]">
        <a-input v-model:value="connectionForm.ip" />
      </a-form-item>

      <a-form-item label="端口" name="port" :rules="[{ required: true, message: '请输入端口!' }]">
        <a-input v-model:value="connectionForm.port" />
      </a-form-item>

      <a-form-item
        label="默认数据库"
        name="database"
        :rules="[{ required: true, message: '请输入默认数据库!' }]"
      >
        <a-input v-model:value="connectionForm.database" />
      </a-form-item>

      <a-form-item
        label="用户名"
        name="username"
        :rules="[{ required: true, message: '请输入用户名!' }]"
      >
        <a-input v-model:value="connectionForm.username" />
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
        :rules="[{ required: true, message: '请输入密码!' }]"
      >
        <a-input-password v-model:value="connectionForm.password" />
      </a-form-item>

      <a-form-item name="remember" :wrapper-col="{ offset: 6, span: 16 }">
        <a-checkbox v-model:checked="connectionForm.remember">保存到本地</a-checkbox>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { Split as ArcoSplit } from '@arco-design/web-vue'
import Sidebar from './sidebar.vue'
import { message as SystemMsg } from 'ant-design-vue'
import { useRouter } from 'vue-router'

const router = useRouter()
const { ipcRenderer } = window.electron
const sidebarRef = ref()
const splitSize = ref(0.2)
const ws = ref()
const isConnected = ref(false)
const isExecuting = ref(false)
const executionTime = ref(0)
const queryResult = ref(null)
const errorMessage = ref('')
const queryHistory = ref([])
const sqlQuery = ref('SHOW DATABASES;')
const newConnectionModal = ref(false)
const connectionForm = reactive({
  connectionName: '47.97.194.8',
  ip: '47.97.194.8',
  port: '9041',
  username: 'root',
  password: 'yanboot',
  remember: false,
  database: 'yanboot_iot_dev'
})
let queryId = 1

const handleToQuery = () => {
  console.log('handleToQuery')
  router.push('/query')
}

//打开新建连接弹窗
const handleNewConnection = () => {
  newConnectionModal.value = true
}

//新建连接
const handleSaveConn = async () => {
  console.log('保存连接信息', connectionForm)
  try {
    const { result, message } = await invokeMainProcess('connect-to-tdengine', connectionForm)
    if (result) {
      SystemMsg.success('连接成功')
      if (connectionForm.remember) {
        console.log('保存连接信息', connectionForm)
        const connList = [connectionForm]
        await ipcRenderer.send('setValue', 'connList', JSON.stringify(connList))
      }
      connectionOnFinish()
    } else {
      SystemMsg.error('连接失败：' + message)
    }
  } catch (err) {
    SystemMsg.error('IPC 调用失败：' + err.message)
  }
}

//调用主进程方法
const invokeMainProcess = async (methodName, args) => {
  try {
    const { result, message } = await ipcRenderer.invoke(methodName, JSON.stringify(args))
    return { result, message }
  } catch (err) {
    console.error('IPC 调用失败：', err)
    return null
  }
}

//重置连接信息
const resetConnectionInfo = () => {
  connectionForm.connectionName = ''
  connectionForm.ip = ''
  connectionForm.port = ''
  connectionForm.username = ''
  connectionForm.password = ''
  connectionForm.remember = false
  connectionForm.database = ''
}

//关闭新建连接弹窗
const connectionOnFinish = () => {
  resetConnectionInfo()
  newConnectionModal.value = false
}

const handleQuery = () => {
  if (!isConnected.value) {
    console.warn('WebSocket not connected yet.')
    return
  }
  showDataBase()
}

const showDataBase = () => {
  console.log('查询所有数据库')
  if (!isConnected.value || isExecuting.value) return

  isExecuting.value = true
  errorMessage.value = ''
  queryResult.value = null
  const currentQueryId = queryId++
  const startTime = performance.now()

  ws.value.send(
    JSON.stringify({
      id: currentQueryId,
      type: 'query|sidebar|showDataBases',
      payload: {
        sql: sqlQuery.value
      }
    })
  )

  const timer = setInterval(() => {
    if (!isExecuting.value) {
      clearInterval(timer)
    } else {
      executionTime.value = Math.round(performance.now() - startTime)
    }
  }, 10)
}

// const connectWebSocket = () => {
//   ws.value = new WebSocket(`ws://127.0.0.1:8081`)
//
//   ws.value.onopen = () => {
//     console.log('Connected to WebSocket server')
//     isConnected.value = true
//   }
//
//   ws.value.onmessage = (event) => {
//     const response = JSON.parse(event.data)
//     console.log('response result', response)
//     const queryType = response.type.split('|')
//     if (queryType[0] === 'query') {
//       isExecuting.value = false
//       queryResult.value = response.payload
//       errorMessage.value = ''
//
//       //处理分发
//       switch (queryType[1]) {
//         case 'sidebar':
//           switch (queryType[2]) {
//             case 'showDataBases':
//               console.log('798')
//               sidebarRef.value?.initData(response.payload)
//               break
//           }
//           break
//         case 'user':
//           break
//       }
//       // Add to history
//       queryHistory.value.unshift({
//         id: response.id,
//         sql: sqlQuery.value,
//         result: response.payload,
//         timestamp: new Date(),
//         duration: executionTime.value
//       })
//
//       // Keep only last 20 queries
//       if (queryHistory.value.length > 20) {
//         queryHistory.value.pop()
//       }
//     } else if (response.type === 'error') {
//       isExecuting.value = false
//       errorMessage.value = response.payload
//       queryResult.value = null
//     } else if (queryType[0] === 'insert') {
//     } else if (queryType[0] === 'update') {
//     } else if (queryType[0] === 'delete') {
//     }
//   }
//
//   ws.value.onerror = (error) => {
//     console.error('WebSocket error:', error)
//     isConnected.value = false
//   }
//
//   ws.value.onclose = () => {
//     console.log('WebSocket connection closed')
//     isConnected.value = false
//     // Attempt to reconnect after 5 seconds
//     setTimeout(connectWebSocket, 5000)
//   }
// }

onMounted(() => {
  // connectWebSocket()
})

// onBeforeUnmount(() => {
//   ws.value.close()
// })
</script>

<style scoped>
:where(.css-dev-only-do-not-override-1p3hq3p).ant-layout .ant-layout-header {
  padding-inline: 0 !important;
  line-height: normal !important;
}

:deep(.arco-split-trigger-icon) {
  margin: -4px;
}

.layout {
  height: 100%;
  width: 100%;
  margin: 0;
  padding: 0;
}

.layout_head {
  background-color: #f0f0f0;
  height: 60px;
  width: 100%;
}

.layout_head > div:first-child {
  display: flex;
  margin-left: 20px;
  height: 100%;
}

.layout_head > div:first-child div {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 80px;
}

.layout_head > div:first-child img {
  height: 25px;
  width: 25px;
}

.layout_head > div:first-child div:hover {
  background-color: #d6ecff;
  cursor: pointer;
}

.layout_head > .ant-space:first-child .ant-space-item img {
  width: 25px !important;
  height: 25px !important;
}

.layout_head > .ant-space:first-child .ant-space-item div {
  color: black !important;
  font-size: 12px !important;
}

.page-container {
  height: 100%;
  overflow: hidden;
}

:deep(.arco-split-trigger-icon-wrapper svg) {
  visibility: hidden;
}
</style>
